#!/bin/bash

# Java 应用管理脚本
APP_NAME="wechat-login"
JAR_FILE="/opt/wechat-login-0.0.1-SNAPSHOT.jar"
PID_FILE="/var/run/$APP_NAME.pid"
LOG_FILE="/var/log/$APP_NAME.log"

JAVA_OPTS="-Xms512m -Xmx1024m -server"
SPRING_OPTS="--spring.profiles.active=prod"

start() {
    if [ -f "$PID_FILE" ]; then
        PID=$(cat $PID_FILE)
        if ps -p $PID > /dev/null; then
            echo "$APP_NAME is already running (PID: $PID)"
            return 1
        else
            rm -f $PID_FILE
        fi
    fi

    mkdir -p $(dirname $LOG_FILE)
    nohup java $JAVA_OPTS -jar $JAR_FILE $SPRING_OPTS > $LOG_FILE 2>&1 &
    echo $! > $PID_FILE
    echo "$APP_NAME started with PID $(cat $PID_FILE)"
}

stop() {
    if [ ! -f "$PID_FILE" ]; then
        echo "$APP_NAME is not running"
        return 1
    fi

    PID=$(cat $PID_FILE)
    if ps -p $PID > /dev/null; then
        echo "Stopping $APP_NAME (PID: $PID)..."
        kill $PID
        
        TIMEOUT=30
        while [ $TIMEOUT -gt 0 ] && ps -p $PID > /dev/null; do
            sleep 1
            TIMEOUT=$((TIMEOUT - 1))
        done
        
        if ps -p $PID > /dev/null; then
            echo "Force killing $APP_NAME..."
            kill -9 $PID
        fi
    else
        echo "$APP_NAME is not running (PID: $PID)"
    fi
    
    rm -f $PID_FILE
    echo "$APP_NAME stopped"
}

status() {
    if [ ! -f "$PID_FILE" ]; then
        echo "$APP_NAME is not running"
        return 1
    fi

    PID=$(cat $PID_FILE)
    if ps -p $PID > /dev/null; then
        echo "$APP_NAME is running (PID: $PID)"
    else
        echo "$APP_NAME is not running but PID file exists"
    fi
}

restart() {
    stop
    sleep 2
    start
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status
        ;;
    restart)
        restart
        ;;
    *)
        echo "Usage: $0 {start|stop|status|restart}"
        exit 1
        ;;
esac

exit 0
